//
//  PhotoMapView.m
//  BabyHelper
//
//  Created by  thomas on 11-8-26.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PhotoMapView.h"

@implementation PhotoMapView
@synthesize mapView;
@synthesize photoAnnotations;
@synthesize babyPhotos;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.babyPhotos = [[NSMutableArray alloc]init];
	self.photoAnnotations = [[NSMutableArray alloc]init];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillDisappear:(BOOL)animated{
	self.mapView.delegate = nil;
}



- (void)dealloc {
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated{
	self.mapView.delegate = self;
	[super viewWillAppear:animated];
}

-(void)UpdateAnnotations{
	Dao *dao = [Dao getInstance];	
	[self.babyPhotos removeAllObjects];
	
	NSString *whereClause = @"WHERE categoryID = 0 and thumpath != 'null' and latitude != '0' and longitude != '0' and location != '' ORDER BY TIMESTAMP DESC";
	[dao QueryBabyPhotoEntryWith:whereClause records:self.babyPhotos];	
	
	[self AddPhotoAnnotationToMap];
	[self ResizeMapAccordingLocations];
}

- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
	MKPinAnnotationView *pinView = nil;
	PhotoAnnotation *photoAnnotation = annotation;
	static NSString *defaultPinID = @"com.ibabynotes.pin";
	pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
	if ( pinView == nil ) pinView = [[[MKPinAnnotationView alloc]
									  initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
	pinView.pinColor = MKPinAnnotationColorRed;
	pinView.canShowCallout = YES;
	pinView.animatesDrop = YES;
	//pinView.image
	// Set up the Left callout
	UIButton *photoAnnotationButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	photoAnnotationButton.frame = CGRectMake(0, 0, 23, 23);
	photoAnnotationButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	photoAnnotationButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	NSString *whereClause = [NSString stringWithFormat:@"WHERE categoryID = 0 and thumpath != 'null' and location = '%@'", photoAnnotation.location];
	[photoAnnotationButton setTitle:whereClause forState:UIControlStateNormal];
	[photoAnnotationButton addTarget:self action:@selector(checkButtonTapped:event:)forControlEvents:UIControlEventTouchUpInside];
	
	pinView.rightCalloutAccessoryView = photoAnnotationButton;
	return pinView;
}

-(void)AddPhotoAnnotationToMap{
	
	static float tmp_latitude = 0.01f;
	static float tmp_longitude = 0.01f;
	[self.photoAnnotations removeAllObjects];
	for(BabyPhotoEntry *entry in self.babyPhotos)
	{
		CLLocationCoordinate2D coordinate;
		coordinate.latitude  = entry.latitude;
		coordinate.longitude = entry.longitude;
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setDateFormat:DATE_FORMAT];
		PhotoAnnotation *ann = [[[PhotoAnnotation alloc] initWithCoordinate:coordinate
															 annotationType:AnnotationTypeDateLocation
																	  title:entry.location
																	  location:entry.location
																	  comments:entry.comments								 
																	  timeString:[dateFormatter stringFromDate:entry.timestamp]] autorelease];
			
		[dateFormatter release];			
		[photoAnnotations addObject:ann];
	}
	[self.mapView addAnnotations:photoAnnotations];	
}


-(void)ResizeMapAccordingLocations{
	
	if([self.photoAnnotations count] <= 1)
		return;
	
	PhotoAnnotation* first = (PhotoAnnotation *)[self.photoAnnotations objectAtIndex:0];
	CLLocationDegrees minLat = first.coordinate.latitude;
	CLLocationDegrees minLon = first.coordinate.longitude;
	CLLocationDegrees maxLat = first.coordinate.latitude;
	CLLocationDegrees maxLon = first.coordinate.longitude;
	
	for(PhotoAnnotation *info in self.photoAnnotations)
	{
		if( minLat > info.coordinate.latitude )
			minLat = info.coordinate.latitude;
		if( minLon > info.coordinate.longitude )
			minLon = info.coordinate.longitude;
		if( maxLat < info.coordinate.latitude )
			maxLat = info.coordinate.latitude;
		if( maxLon < info.coordinate.longitude )
			maxLon = info.coordinate.longitude;
	}
	
	CLLocationCoordinate2D southWest;
	CLLocationCoordinate2D northEast;	
	southWest.latitude  = minLat;
	southWest.longitude = minLon;
	northEast.latitude  = maxLat;
	northEast.longitude = maxLon;
	
	CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:southWest.latitude longitude:southWest.longitude];
	CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:northEast.latitude longitude:northEast.longitude];
	
	// This is a diag distance (if you wanted tighter you could do NE-NW or NE-SE)
	CLLocationDistance meters = [locSouthWest getDistanceFrom:locNorthEast];
	
	MKCoordinateRegion region;
	CLLocationCoordinate2D center;
	center.latitude  = (southWest.latitude + northEast.latitude) / 2.0;
	center.longitude = (southWest.longitude + northEast.longitude) / 2.0;
	region.center    = center;
	NSLog(@"center location %f,%f",center.latitude,center.longitude);
	region.span.latitudeDelta  = meters / 111319.5;
	region.span.longitudeDelta = 0.05f;
	[self.mapView setRegion:region animated:YES];
	
	//theRegion = [mapView regionThatFits:region];
	//[mapView setRegion:theRegion animated:YES];
	
	[locSouthWest release];
	[locNorthEast release];
}

- (void)checkButtonTapped:(id)sender event:(id)event {	

	UIButton *button = sender;
	[PhotoSet updateBabyPhotoSet:button.currentTitle photoCategory:-1];
	BabyGrowPhotoView *childView = [[BabyGrowPhotoView alloc]init];
	childView.whereClause   = button.currentTitle;
	childView.photoCategory = -1;
	[self.navigationController pushViewController:childView animated:YES];
	[childView release];
	
}

@end
